import globalWSManager from './global-manager.js'

/**
 * 获取全局WebSocket连接统计信息
 */
export function getWebSocketStats() {
  return globalWSManager.getConnectionStats()
}

/**
 * 关闭所有WebSocket连接
 */
export function closeAllWebSocketConnections() {
  globalWSManager.closeAllConnections()
}

/**
 * 获取全局WebSocket管理器（用于调试）
 */
export function getGlobalWebSocketManager() {
  return globalWSManager
}

/**
 * 调试工具：检查WebSocket连接状态
 */
export function debugWebSocketConnections() {
  const stats = getWebSocketStats()
  console.log('=== WebSocket连接调试信息 ===')
  console.log('总连接数:', stats.totalConnections)
  console.log('连接详情:', stats.connections)
  
  // 检查是否有重复连接
  const connectionKeys = new Set()
  const duplicates = []
  
  stats.connections.forEach(conn => {
    if (connectionKeys.has(conn.key)) {
      duplicates.push(conn.key)
    } else {
      connectionKeys.add(conn.key)
    }
  })
  
  if (duplicates.length > 0) {
    console.warn('发现重复连接:', duplicates)
  }
  
  console.log('=== 调试信息结束 ===')
  return stats
}

/**
 * 清理无效连接
 */
export function cleanupInvalidConnections() {
  const stats = getWebSocketStats()
  let cleanedCount = 0
  
  stats.connections.forEach(conn => {
    if (!conn.isConnected && !conn.isConnecting) {
      // 如果连接既未连接也未在连接中，可能是无效连接
      console.log('清理无效连接:', conn.key)
      globalWSManager.unregisterConnection(
        conn.key.split('_')[0], // 连接类型
        conn.key.split('_')[1] || '', // roomId
        conn.key.split('_')[2] || '' // gameType
      )
      cleanedCount++
    }
  })
  
  console.log(`清理了 ${cleanedCount} 个无效连接`)
  return cleanedCount
}

/**
 * 获取连接状态统计
 */
export function getConnectionStatusSummary() {
  const stats = getWebSocketStats()
  const summary = {
    total: stats.totalConnections,
    connected: 0,
    connecting: 0,
    disconnected: 0,
    byType: {
      roomList: 0,
      gameRoom: 0,
      chatRoom: 0
    }
  }
  
  stats.connections.forEach(conn => {
    if (conn.isConnected) {
      summary.connected++
    } else if (conn.isConnecting) {
      summary.connecting++
    } else {
      summary.disconnected++
    }
    
    // 按类型统计
    if (conn.key.startsWith('roomList')) {
      summary.byType.roomList++
    } else if (conn.key.startsWith('gameRoom')) {
      summary.byType.gameRoom++
    } else if (conn.key.startsWith('chatRoom')) {
      summary.byType.chatRoom++
    }
  })
  
  return summary
}

/**
 * 检查连接健康状态
 */
export function checkConnectionHealth() {
  const stats = getWebSocketStats()
  const health = {
    isHealthy: true,
    issues: [],
    recommendations: []
  }
  
  // 检查连接数量
  if (stats.totalConnections > 10) {
    health.isHealthy = false
    health.issues.push('连接数量过多')
    health.recommendations.push('考虑关闭不必要的连接')
  }
  
  // 检查重复连接
  const connectionKeys = new Set()
  const duplicates = []
  stats.connections.forEach(conn => {
    if (connectionKeys.has(conn.key)) {
      duplicates.push(conn.key)
    } else {
      connectionKeys.add(conn.key)
    }
  })
  
  if (duplicates.length > 0) {
    health.isHealthy = false
    health.issues.push('存在重复连接')
    health.recommendations.push('清理重复连接')
  }
  
  // 检查长时间未活动的连接
  const now = Date.now()
  const inactiveThreshold = 5 * 60 * 1000 // 5分钟
  stats.connections.forEach(conn => {
    if (now - conn.lastActivity > inactiveThreshold) {
      health.issues.push(`连接 ${conn.key} 长时间未活动`)
      health.recommendations.push('清理长时间未活动的连接')
    }
  })
  
  return health
} 